<?php
/**
 * 公共函数文件
 * @author Jerry
 * @version 1.0
 */


/**
  * 解析调式信息,得到客户段信息,如IP等
  */
function parse_incoming()
{
	global $_GET, $_POST, $HTTP_CLIENT_IP, $REQUEST_METHOD, $REMOTE_ADDR, $HTTP_PROXY_USER, $HTTP_X_FORWARDED_FOR;
	$return = array();

	if( is_array($_GET) )
	{
		while( list($k, $v) = each($_GET) )
		{
			if( is_array($_GET[$k]) )
			{
				while( list($k2, $v2) = each($_GET[$k]) )
				{
					$return[$k][ clean_key($k2) ] = clean_value($v2);
				}
			}
			else
			{
				$return[$k] = clean_value($v);
			}
		}
	}

	// Overwrite GET data with post data

	if( is_array($_POST) )
	{
		while( list($k, $v) = each($_POST) )
		{
			if ( is_array($_POST[$k]) )
			{
				while( list($k2, $v2) = each($_POST[$k]) )
				{
					$return[$k][ clean_key($k2) ] = clean_value($v2);
				}
			}
			else
			{
				$return[$k] = clean_value($v);
			}
		}
	}

	//----------------------------------------
	// Sort out the accessing IP
	// (Thanks to Cosmos and schickb)
	//----------------------------------------

	$addrs = array();

	foreach( array_reverse( explode( ',', $HTTP_X_FORWARDED_FOR ) ) as $x_f )
	{
		$x_f = trim($x_f);

		if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $x_f ) )
		{
			$addrs[] = $x_f;
		}
	}

	$addrs[] = $_SERVER['REMOTE_ADDR'];
	$addrs[] = $HTTP_PROXY_USER;
	$addrs[] = $REMOTE_ADDR;
	//header("Content-type: text/plain"); print_r($addrs); print $_SERVER['HTTP_X_FORWARDED_FOR']; exit();

	$return['IP_ADDRESS'] = select_var( $addrs );

	// Make sure we take a valid IP address

	$return['IP_ADDRESS'] = preg_replace( "/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", "\\1.\\2.\\3.\\4", $return['IP_ADDRESS'] );

	$return['request_method'] = ( $_SERVER['REQUEST_METHOD'] != "" ) ? strtolower($_SERVER['REQUEST_METHOD']) : strtolower($REQUEST_METHOD);
	$data = explode(';',$return[op]);
	foreach($data as $key=>$var) 
	{
		$data1 = explode('::', $var);
		$return["{$data1[0]}"] = $data1[1];
	}
	//debug($return);

	return $return;
}


function clean_key($key)
{

	if ($key == "")
	{
		return "";
	}
	$key = preg_replace( "/\.\./"           , ""  , $key );
	$key = preg_replace( "/\_\_(.+?)\_\_/"  , ""  , $key );
	$key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
	return $key;
}

function clean_value($val)
{

	if ($val == "")
	{
		return "";
	}

	if ( get_magic_quotes_gpc() )
	{
		$val = stripslashes($val);
	}

	return $val;
}

function select_var($array) {

	if ( !is_array($array) ) return -1;

	ksort($array);


	$chosen = -1;  // Ensure that we return zero if nothing else is available

	foreach ($array as $k => $v)
	{
		if (isset($v))
		{
			$chosen = $v;
			break;
		}
	}

	return $chosen;
}

function add_slashes($string)
{
	if(!$GLOBALS['magic_quotes_gpc'])
	{
		if(is_array($string))
		{
			foreach($string as $key => $val)
			{
				$string[$key] = add_slashes($val);
			}
		}
		else
		{
			$string = addslashes($string);
		}
	}
	return $string;
}

/**
  * 显示调式信息
  */
function debug($str = '')
{
	global $db,$in_var,$logger;

	echo '<br>';
	print_r($in_var);
	echo "<br>Time : " . $logger->dumpTime();
	echo $db->logger->dumpQueries();
	if($str)
	{
		echo '<hr>';
		print_r($str);
	}

}

function show_message($message, $url_forward = '',$delay = '3', $js = '', $close = '')
{

	if($js == 'confirm')
	{
		$message = "<script>\n"
		. "if(confirm(\"" . $message
		. "  是否返回？\")) parent.location=\""
		. $url_forward
		. "\"\n"
		."</script>\n";

		echo $message;
		exit;
	}
	elseif($js == 'alert')
	{
		if($close)
		{
			$message = "<script>alert(\""
			. $message . "窗口自动关闭\")\n"
			. "window.self.close()\n"
			. "</script>";
		}
		else
		{
			$message = "<script>alert(\"" . $message . "\")\n"
			."document.location='" . $url_forward . "'\n"
			."</script>";
		}

		echo $message;
		exit;
	}
	else
	{
		global $tpl,$admin_lang;

		$tpl->assign('Delay',$delay);
		$tpl->assign('UrlForward',$url_forward);
		$tpl->assign('Message',$message);

		$tpl->display('sys_error.html');
		exit;
	}
}

function goto($url,$type = 'header',$target = 'document')
{
	if($type == 'header') 
	{
		header("location: " . $url);
		exit;
	}
	elseif($type == 'js')
	{
		echo "<script>" . $target . ".location='" . $url . "'\n" . "</script>";
		exit;
	}
}

function page($page_num,$current_page,$send_var)
{
	global $admin_lang;

	if($page_num == '')
	return false;
	$header = floor(($current_page - 1)/10);

	$start = $header*10 + 1;
	//$send_var = str_replace("{ChannelID}", $ChannelID,$send_var);

	for($i= $start;$i<=$start + 9;$i++)
	{
		$link = str_replace("{Page}", $i,$send_var);

		if($current_page == $i)
		{
			$page.= "<b>".$i."</b>&nbsp;";
		}
		else
		{
			$page.= "<a href='".$link."'>[".$i."]</a>&nbsp;";
		}
		if($i==$page_num) break;
	}

	if ($current_page < $page_num)
	{
		$link1= str_replace("{Page}", $current_page+1 ,$send_var);
		$page = $page . "&nbsp;<b><a href='".$link1."' >下一页</a></b>";
	}

	if($current_page > 1) {
		if(($current_page-1) == 0)
		$link1 = str_replace("{Page}", 0,$send_var);
		else
		$link1= str_replace("{Page}" , $current_page-1 ,$send_var);
		$page= "<b><a href='".$link1."' >上一页</a></b>&nbsp;&nbsp;".$page;
	}



	if((($start + 10)) <= $page_num) {
		$i =  $start + 10;
		$link = str_replace("{Page}", $i,$send_var);
		$page= $page."&nbsp;&nbsp;<b><a href='".$link."' >下十页</a></b>";
	}

	if(($start - 1) > 0)
	{
		$i =  $start - 10;
		$link = str_replace("{Page}", $i,$send_var);
		$page= "<b><a href='".$link."' >上十页</a></b>&nbsp;&nbsp;".$page;
	}

	return $page;

}



function CsubStr($str,$start,$end,$sss='...') {
	/*
	UTF-8 version of substr(), for people who can't use mb_substr() like me.
	Length is not the count of Bytes, but the count of UTF-8 Characters

	Author: Windix Feng
	Bug report to: windix(AT)263.net, http://www.douzi.org/blog

	- History -
	1.0 2004-02-01 Initial Version
	2.0 2004-02-01 Use PREG instead of STRCMP and cycles, SPEED UP!
	*/
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $str, $ar);

	if(func_num_args() >= 3)
	{
		$end = func_get_arg(2);
		if(count($ar[0])>$end)
		{
			$str = join("",array_slice($ar[0],$start,$end)).$sss;
		}
		else
		{
			$str = $str;
		}
	}
	else
	{
		$str = join("",array_slice($ar[0],$start)).$sss;
	}

	$patt = "/(<[^>]*\.\.\.)/";
	preg_match_all($patt, $str, $matches);
	$replace_str = $matches[1][0];
	$str = str_replace($replace_str, "...", $str);

	return $str;
}


//高亮关键字
function HighLight($Content,$KeyWords,$Num = '')
{
	$HighLightKeyWords = "<font color=red>$KeyWords</font>";
	$Content = str_replace($KeyWords,$HighLightKeyWords,$Content);
	if(!empty($Num)){
		$Content = CsubStr($Content,$Num);
	}
	return $Content;


}


function deldir($dir)
{
	$dh = opendir($dir);
	
	while ($file=readdir($dh)) 
	{
		if($file!="." && $file!="..") 
		{
			$fullpath=$dir."/".$file;
			if(!is_dir($fullpath)) 
			{
				unlink($fullpath);
			} else 
			{
				deldir($fullpath);
			}
		}
	}
	
	closedir($dh);
	
	if(rmdir($dir)) 
	{
		return true;
	} 
	else 
	{
		return false;
	}
}

//缩略图片
function AutoImg($srcFile,$toW="120",$toH="160",$toFile="../upload/tmp/")
{
	global $html , $sys_conf_var;

	if(!is_dir($toFile)){
		$html->createdir($toFile);
	}

	if($toFile==""){ $toFile = $srcFile; }
	else
	{
		$file_type = explode('.',$srcFile);
		$cdn_url = $sys_conf_var['server']['cdn'] . "/upload/tmp/" . md5($srcFile . $toW . $toH) . '.' . end($file_type);

		if(is_file($toFile = $toFile . md5($srcFile . $toW . $toH) . '.' . end($file_type)))
		{
			return $cdn_url;
		}
	}

	$info = "";
	$data = GetImageSize($srcFile,$info);

	switch ($data[2])
	{
		case 1:
			if(!function_exists("imagecreatefromgif")){
				echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！";
				exit();
			}
			$im = ImageCreateFromGIF($srcFile);
			break;
		case 2:
			if(!function_exists("imagecreatefromjpeg")){
				echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！";
				exit();
			}
			$im = ImageCreateFromJpeg($srcFile);
			break;
		case 3:
			$im = ImageCreateFromPNG($srcFile);
			break;
		case 6:
			return $srcFile;
			break;
	}

	$srcW=ImageSX($im);
	$srcH=ImageSY($im);

	/*if($srcW > $srcH)
	{
	$ftoH = $toH;
	$ftoW = $srcW * ($toH/$srcH);
	}
	else
	{
	$ftoW = $toW;
	$ftoH = $srcH * ($toW/$srcW);
	}*/
	$ftoH = $toH;
	$ftoW = $srcW * ($toH/$srcH);

	if($ftoW < $toW)
	{
		$ftoH = $ftoH * ($toW/$ftoW);
		$ftoW = $toW;
	}
	/*$toWH=$toW/$toH;
	$srcWH=$srcW/$srcH;
	if($toWH<=$srcWH){
	$ftoW=$toW;
	$ftoH=$ftoW*($srcH/$srcW);
	}
	else{
	$ftoH=$toH;
	$ftoW=$ftoH*($srcW/$srcH);
	}    */

	if($srcW>$toW||$srcH>$toH)
	{
		if(function_exists("imagecreatetruecolor")){
			$ni = ImageCreateTrueColor($toW,$toH);
			if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			else{
				$ni=ImageCreate($toW,$toH);
				ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			}
		}else{
			$ni=ImageCreate($toW,$toH);
			ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		}

		if(function_exists('imagejpeg')) ImageJpeg($ni,$toFile,100);
		else ImagePNG($ni,$toFile);
		ImageDestroy($ni);
	}
	else
	{
		return $srcFile;
	}

	ImageDestroy($im);

	//return $toFile;
	return $cdn_url;
}

function __autoload($className) 
{
    if (file_exists(CLASS_DIR . strtolower($className) . '.class.php')) 
    {
        require_once(CLASS_DIR. strtolower($className) . '.class.php');
    } 
    else if (file_exists(CONTROLLER_DIR . strtolower($className) . '.class.php')) 
    {
        require_once(CONTROLLER_DIR . strtolower($className) . '.class.php');
    } 
    else if (file_exists(MODEl_DIR . strtolower($className) . '.class.php')) 
    {
        require_once(MODEl_DIR . strtolower($className) . '.class.php');
    } 
    else 
    {
        /* Error Generation Code Here */
    }
}

function show_error_msg($msg)
{
	echo '<div id="error_msg">' . $msg . '</div>';
}


function get_order($order,$parm)
{
	
	if($sort = explode(',',$parm))
	{
		foreach ($sort as $var)
		{
			if($var == '-' . $order)
			{
				return $order . str_replace(',-' . $order,'',$parm);
			}
			elseif($var == $order)
			{
				return '-' . $order . str_replace(',' . $order,'',$parm);
			}
		}
	}

	return $order . $parm;
}

function fotmat_bit($num)
{
	$bitunit = array(' B',' KB',' MB',' GB');
	for($key=0;$key<count($bitunit);$key++){
		if($num>=pow(2,10*$key)-1){ //1023B 会显示为 1KB
			$num_bitunit_str=(ceil($num/pow(2,10*$key)*100)/100)." $bitunit[$key]";
		}
	}
	return $num_bitunit_str;
}


function getCategoryURL($id,$page=1)
{
	return "index.php?c=category&id=" . $id;
}

function getAreaURL($id,$page=1)
{
	return "index.php?c=area&id=" . $id;
}
?>